# frozen_string_literal: true
require 'fastlane/action'

module Fastlane
  module Actions
    class ElexBuildIosAction < Action
      def self.run(params)
        print_environment
        FastlaneCore::PrintTable.print_values(
          config: params,
          title: 'build config'
        )

        # other_action.cocoapods

        app_identifiers = []
        main_target_bundle_id = params[:bundle_id]
        app_identifiers << main_target_bundle_id if main_target_bundle_id
        main_target_name = params[:main_target_name]
        team_id = params[:team_id]
        code_sign_identity = params[:code_sign_identity]


        # Match
        other_action.match(
          app_identifier: app_identifiers.join(","),
          type: params[:signingCertificate_type],
          storage_mode: "git",
          git_url: params[:signingCertificate_git_url],
          git_branch: params[:signingCertificate_branch],
          readonly: true
        )
        UI.success("Match action has been successfully called!")

        UI.success("[Elex] update code signing setting begin")

        code_sign_setting = {}
        code_sign_setting['BundleIDs'] = main_target_bundle_id;
        code_sign_setting['Podfile Name'] = params[:profile_name];


        # 修改project
        other_action.update_code_signing_settings(
          # 改为手动签名
          use_automatic_signing: false,
          # Target名称
          targets:main_target_name,
          # 修改成的bundleID
          bundle_identifier:main_target_bundle_id,
          # 证书的TeamID
          team_id:team_id,
          # 签名证书的identity（Apple Developer,iPhone Developer）
          code_sign_identity:code_sign_identity,
          # 证书profile名称
          profile_name:params[:profile_name]
        )

        UI.success("[Elex] update code signing setting success")

        other_action.gym(
          workspace: params[:workspace],
          project: params[:project],
          # 指定项目的 scheme 名称
          scheme: main_target_name,
          # 每次打包之前clean一下
          clean: true,
          # 指定输出ipa包的文件夹地址
          output_directory: params[:output_directory],
          # 输出ipa的文件名
          output_name: params[:output_name],
          # 指定打包方式 (可选: Release, Debug)
          configuration: params[:configuration],
          #  Hide all information that's not necessary while building
          silent: true,
          # The name of the code signing identity to use.
          codesigning_identity: code_sign_identity,
          # ipa文件是否包含symbols
          include_symbols: true,
          # 关闭bitcode
          include_bitcode: false,
          # 归档文件路径
          archive_path: params[:archive_path],
          # 指定打包所使用的输出方式 (可选: app-store, package, ad-hoc, enterprise, development)
          export_method: params[:export_method],
          export_options: {
            signingCertificate: code_sign_identity
          }
        )

        Actions.lane_context[:ELEX_BUILD_IPA_OUTPUT_PATH] = Actions.lane_context[:IPA_OUTPUT_PATH]
        Actions.lane_context[:ELEX_BUILD_ARCHIVE_OUTPUT_PATH] = Actions.lane_context[:XCODEBUILD_ARCHIVE]
        Actions.lane_context[:ELEX_BUILD_DSYM_OUTPUT_PATH] = Actions.lane_context[:DSYM_OUTPUT_PATH]

        FastlaneCore::PrintTable.print_values(
          config: {
            "ELEX_BUILD_IPA_OUTPUT_PATH" => Actions.lane_context[:ELEX_BUILD_IPA_OUTPUT_PATH],
            "ELEX_BUILD_ARCHIVE_OUTPUT_PATH" => Actions.lane_context[:ELEX_BUILD_ARCHIVE_OUTPUT_PATH],
            "ELEX_BUILD_DSYM_OUTPUT_PATH" => Actions.lane_context[:ELEX_BUILD_DSYM_OUTPUT_PATH]
          },
          title: "构建输出信息"
        )

        Actions.lane_context[:ELEX_BUILD_IPA_OUTPUT_PATH]

      end

      def self.print_environment
        env_info = {}
        env_info["ruby_version"] = `ruby -v`
        env_info['fastlane_version'] = `fastlane -v`
        env_info['xcode_version'] =  `xcodebuild -version`

        FastlaneCore::PrintTable.print_values(
          config:env_info,
          title:'env'
        )
      end

      def self.description
        "elex fastlane build plugins"
      end

      def self.authors
        ["yanlong"]
      end

      def self.output
        [
          ['ELEX_BUILD_IPA_OUTPUT_PATH', 'The path to the newly generated ipa file'],
          ['ELEX_BUILD_ARCHIVE_OUTPUT_PATH', 'The path to the xcodebuild archive'],
          ['ELEX_BUILD_DSYM_OUTPUT_PATH', 'The path to the dSYM files'],
        ]
      end

      def self.return_value
        "The path to the newly generated ipa file"
      end

      def self.details
        "elex fastlane build iOS ipa tool"
      end

      def self.available_options
        [
          FastlaneCore::ConfigItem.new(key: :workspace,
                                       env_name: 'ELEX_BUILD_WORKSPACE',
                                       description: 'Path to the workspace file',
                                       optional: true ,
                                       type: String),
          FastlaneCore::ConfigItem.new(key: :project,
                                       env_name: 'ELEX_BUILD_PROJECT',
                                       description: 'Path to the workspace file',
                                       optional: true ,
                                       type: String),

          FastlaneCore::ConfigItem.new(key: :main_target_name,
                                       env_name: 'ELEX_BUILD_TARGET',
                                       description: 'target name',
                                       optional: false ,
                                       type: String),
          FastlaneCore::ConfigItem.new(key: :bundle_id,
                                       env_name: 'ELEX_BUILD_BUNDIE_ID',
                                       description: 'app identifier',
                                       optional: false ,
                                       type: String),

          FastlaneCore::ConfigItem.new(key: :signingCertificate_type,
                                       env_name: 'ELEX_BUILD_CERTIFICATE_TYPE',
                                       description: 'buid type, can be appstore, adhoc,development',
                                       default_value: "appstore",
                                       optional: true,
                                       type: String),

          FastlaneCore::ConfigItem.new(key: :signingCertificate_git_url,
                                       env_name: 'ELEX_BUILD_SIGNING_CERTIFICATE_GIT_URL',
                                       description: 'URL to the git repo containing all the certificates',
                                       optional: false ,
                                       type: String),

          FastlaneCore::ConfigItem.new(key: :signingCertificate_branch,
                                       env_name: 'ELEX_BUILD_SIGNING_CERTIFICATE_BRANCH',
                                       description: 'Specific git branch to use',
                                       optional: false ,
                                       type: String),

          FastlaneCore::ConfigItem.new(key: :team_id,
                                       env_name: 'ELEX_BUILD_TEAM_ID',
                                       description: 'The ID of your Developer Portal team if you\'re in multiple teams ',
                                       optional: false ,
                                       type: String),
          FastlaneCore::ConfigItem.new(key: :code_sign_identity,
                                       env_name: 'ELEX_BUILD_CODE_SIGN_IDENTITY',
                                       description: 'The name of the code signing identity to use. It has to match the name exactly. e.g. \'iPhone Distribution: SunApps GmbH\'',
                                       optional: false ,
                                       type: String),

          FastlaneCore::ConfigItem.new(key: :profile_name,
                                       env_name: 'ELEX_BUILD_PROFILE_NAME',
                                       description: 'The name of the profile',
                                       optional: false ,
                                       type: String),

          FastlaneCore::ConfigItem.new(key: :configuration,
                                       env_name: 'ELEX_BUILD_CONFIGURATION',
                                       description: 'The configuration to use when building the app. Defaults to \'Release\'',
                                       default_value: "Release",
                                       optional: true ,
                                       type: String),


        FastlaneCore::ConfigItem.new(key: :output_directory,
                                     env_name: 'ELEX_BUILD_OUTPUT_DIRECTORY',
                                     description: 'The directory in which the ipa file should be stored in',
                                     optional: true,
                                     type: String),

          FastlaneCore::ConfigItem.new(key: :output_name,
                                       env_name: 'ELEX_BUILD_OUTPUT_NAME',
                                       description: 'The name of the resulting ipa file',
                                       optional: true,
                                       type: String),
          FastlaneCore::ConfigItem.new(key: :export_method,
                                       env_name: 'ELEX_BUILD_EXPORT_METHOD',
                                       description: 'Method used to export the archive. Valid values are: app-store, validation,ad-hoc, package, enterprise,development, developer-id and mac-application',
                                       default_value: "app-store",
                                       optional: true,
                                       type: String),
        FastlaneCore::ConfigItem.new(key: :archive_path,
                                     env_name: 'ELEX_BUILD_ARCHIVE_PATH',
                                     description: 'The path to the created archive',
                                     optional: true,
                                     type: String),
        ]
      end

      def self.is_supported?(platform)
        [:ios].include?(platform)
        true
      end

    end
  end
end
